﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class GuideBase : MonoBehaviour, ICanvasRaycastFilter
{
    protected Material _material;
    protected Vector3 _center;
    protected RectTransform _target;
    protected Vector3[] _targetCorners = new Vector3[4];

    protected int _index;
    protected Action<int> _doneAction;

    private void Awake()
    {
        transform.GetComponent<Button>()?.onClick.AddListener(OnMaskButtonClick);
    }

    public virtual void Guide(Canvas canvas, RectTransform target)
    {
        _material = transform.GetComponent<Image>().material;

        _target = target;

        _target.GetWorldCorners(_targetCorners);

        //把世界坐标转化成屏幕坐标
        for (int i = 0; i < _targetCorners.Length; i++)
        {
            _targetCorners[i] = ZTool.WorldToScreenPoint(canvas, _targetCorners[i]);
        }

        //计算中心点
        //1------2
        //|      |
        //0------3
        _center.x = _targetCorners[0].x + (_targetCorners[3].x - _targetCorners[0].x) / 2;
        _center.y = _targetCorners[0].y + (_targetCorners[1].y - _targetCorners[0].y) / 2;

        //设置中心点
        _material.SetVector("_Center", _center);
    }

    // Canvas为 Screen Space -Camera 时：应该使用 RectTransformUtility.RectangleContainsScreenPoint(target,sp,canvas.worldCamera);
    public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        return !RectTransformUtility.RectangleContainsScreenPoint(_target, sp);
    }

    public virtual void OnMaskButtonClick()
    {
    }
}